package com.ruoyi.wechart.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.device.domain.SysAppUser;
import com.ruoyi.device.service.ISysAppUserService;
import com.ruoyi.wechart.dmain.WxLoginUser;
import com.ruoyi.wechart.service.IWxLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

import static io.netty.handler.codec.DecoderResult.failure;

/**
 * 微信登录控制器
 * @auth zz
 * @date 2024-01-25 10:16
 */
@RestController
@RequestMapping("/wechart")
public class WxLoginController extends BaseController {
    @Autowired
    ISysAppUserService registerService;

    @Autowired
    private IWxLoginService loginService;

    /**
     * 注册新用户
     * @param appUser
     * @return
     */
    /*@PostMapping("/register")
    public AjaxResult wxRegister(@RequestBody SysAppUser appUser){
        List<SysAppUser> sysAppUsers = sysAppUserService.selectSysAppUserRegCodeList(appUser.getRegCode());
        List<SysAppUser> collect = sysAppUsers.stream().filter(
                user -> user.getRegCode() == appUser.getRegCode()
        ).collect(Collectors.toList());
        if(collect.size() == 0){
            sysAppUserService.insertSysAppUser(appUser);
            return success("注册成功");
        }else{
            return error("学号重复了");
        }
    }*/

    /**
     * 小程序登录
     * @param code 微信预登录code
     * @param userName 登录用户名
     * @param password 登录密码
     * @return
     */
    @PostMapping("/login")
    public AjaxResult wxCodeLogin(String code, String userName, String password){
        WxLoginUser user = loginService.login(code, userName, password);
        return user.getStatus() >= -1 ? success(user) : error(user.getMsg());
    }

    /**
     * 注册新用户
     * @param appUser
     * @return
     */
    @PostMapping("/register")
    public AjaxResult wxRegister(@RequestBody SysAppUser appUser){
        List<SysAppUser> sysAppUserList = registerService.selectSysAppUserRegCodeList(appUser.getRegCode());
        if(sysAppUserList.size() > 0){
            return error("该用户已注册");
        }
        return toAjax(loginService.register(appUser));
    }

}